package com.iamteer;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Guess
 */
@WebServlet("/Guess")
public class Guess extends HttpServlet {
	private static final long serialVersionUID = 1L;
    int answer;
    
    public void newGame() {
		Random random = new Random(System.currentTimeMillis());
		answer = random.nextInt(30) + 1;
		System.out.println(answer);
	}
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Guess() {
        newGame();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String guessStr = request.getParameter("guess");
		Integer guess = null;
		if (guessStr == null || guessStr.isEmpty()) {
			response.sendRedirect(request.getContextPath() + "/guess.jsp");
			return;
		}else {
			guess = Integer.parseInt(guessStr);
		}
		
		String timesStr = request.getParameter("times");
		Integer times = 1;
		if (timesStr != null && !timesStr.isEmpty()) {
			times = Integer.parseInt(timesStr) + 1;
		}
		
		if (times < 5) {
			String msg = "";
			if (guess > answer) {
				msg = "可惜，大了！";
			} else if (guess < answer) {
				msg = "可惜，小了！";
			} else {
				msg = "恭喜你！中得 1000000 元现金大奖！请带身份证到精神病院领取。。。";
				response.getWriter().write("<font color='red'>" + msg + "</font>");
				times = null;
				newGame();
				return;
			}
			request.setAttribute("times", times);
			request.setAttribute("msg", msg);
		} else {
			newGame();
			response.getWriter().write("游戏结束！<a href='" + request.getContextPath() + "/guess.jsp'>" +"再来一盘</a>");
			return;
		}
		request.getRequestDispatcher("/guess.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
